#!/bin/bash

#
# Automated Mikrotik Router Backup
#

source global.sh

for router in $routers

do

        # Router Directory Variable
        directory=/backup/routers/$router

        # Create's the filename of the backup file with the date followed by the router name
        bfile=`date +%m%d%Y-$router`

        # Check if the Router directory exists, if not, create it.
        if [ -d $directory ]; then

                cd $directory

        else

                mkdir -p $directory
                cd $directory

        fi

        # Print What Router We are Backing Up
        echo "Backing Up $router router" > backup

        # SSH to the router with the backup user and export the configuration to a file. We also send output from the command to a file that we will later use for our confirmationa email.
        ssh -p 9122 backup@$router system backup save name=$bfile &> backup2

        # Secure FTP the export file to the backup server. We also send output from the command to a file that we will later use for our confirmationa email.
        sftp -oPort=9122 backup@$router:$bfile.backup &> backup3

        # Append backup2 & backup3 to backup
        cat backup2 backup3 >> backup

        # Check to see if the backup file exists and append success to backup. If it does not exist, append fail to backup.
        if [ -s $bfile.backup ]; then

                echo "Backup of $router router Successful!" >> backup

        else

                echo "Backup of $router router failed! Need to check what went wrong." >> backup

        fi

        # Send Email Confirmation
        mail -s "$router Router Weekly Backup" $email < backup

        # Remove emailed files
        rm -rf backup backup2 backup3

done

# Remove all Router Backups Older than 3 Weeks
find $directory/*.backup -mtime +22 -print | xargs rm -rf
